import javafx.application.Application;
import javafx.beans.property.SimpleStringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class TableViewCellSelectionDemo extends Application {

    @Override
    public void start(Stage stage) {
        TableView<Person> tableView = new TableView<>();
        tableView.setEditable(true);
        tableView.setTableMenuButtonVisible(true);

        // 启用单元格选择而不是整行选择
        tableView.getSelectionModel().setCellSelectionEnabled(true);
        tableView.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);

        TableColumn<Person, String> nameCol = new TableColumn<>("姓名");
        nameCol.setCellValueFactory(data -> data.getValue().nameProperty());

        TableColumn<Person, String> ageCol = new TableColumn<>("年龄");
        ageCol.setCellValueFactory(data -> data.getValue().ageProperty());

        tableView.getColumns().addAll(nameCol, ageCol);

        // 模拟数据
        ObservableList<Person> data = FXCollections.observableArrayList(
                new Person("张三", "18"),
                new Person("李四", "20"),
                new Person("王五", "22")
        );
        tableView.setItems(data);

        // 可选：添加鼠标拖动监听器（辅助提示）
        tableView.addEventFilter(MouseEvent.MOUSE_DRAGGED, event -> {
            // System.out.println("Dragging cell...");
        });

        VBox root = new VBox(tableView);
        Scene scene = new Scene(root, 400, 300);
        stage.setScene(scene);
        stage.setTitle("JavaFX TableView 单元格多选示例");
        stage.show();
    }

    public static class Person {
        private final SimpleStringProperty name;
        private final SimpleStringProperty age;

        public Person(String name, String age) {
            this.name = new SimpleStringProperty(name);
            this.age = new SimpleStringProperty(age);
        }

        public SimpleStringProperty nameProperty() { return name; }
        public SimpleStringProperty ageProperty() { return age; }
    }

    public static void main(String[] args) {
        launch(args);
    }
}